package com.mq.consumer;

import com.mq.domain.Person;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.swing.JOptionPane;
import org.apache.activemq.ActiveMQConnectionFactory;

 
public class Consumer {
 
    public void consumeMessage(String queueName){
        //Create ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        try{
            //Create Connection
            Connection connection = connectionFactory.createConnection();
            //Start/restart a connection
            connection.start();
             
            //Create Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //Create Queue
            Destination queue = session.createQueue(queueName);
            //Create Consumer
            MessageConsumer consumer = session.createConsumer(queue);
    
            System.out.println("Consumer waiting...");
  
      //Consume Message. Call block until message is received or until close is called
      Message message = consumer.receive();
             
            if(message instanceof ObjectMessage){
        ObjectMessage message2 = (ObjectMessage)consumer.receive();
                Person p = (Person)message2.getObject();
                System.out.println("Received"+p.getName());  
            }else{
                System.out.println("Received message of unknown type");
            }
            
            //Display Message
            //System.out.println("Received message: "+p.getName());
            //Close Consumer
            consumer.close();
            //Close Session
            session.close();
            //Close Connection
            connection.close();
         
        }catch(JMSException e){         
            System.out.println("Problem creating connection to ActiveMQ");
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
    } 
} 